<template>
  <div class="book-detail">
    <n-button @click="$router.back()" style="margin-bottom: 16px;">
      <template #icon><ArrowBackOutline /></template>
      返回
    </n-button>
    
    <n-card v-if="book">
      <n-space vertical size="large">
        <n-space align="center">
          <n-avatar
            :size="120"
            :src="book.cover"
            fallback-src="https://via.placeholder.com/120?text=Book"
          />
          <div>
            <h1>{{ book.title }}</h1>
            <n-space>
              <n-tag>{{ book.author }}</n-tag>
              <n-tag type="info">{{ book.publisher }}</n-tag>
              <n-tag :type="book.availableStock > 0 ? 'success' : 'error'">
                库存: {{ book.availableStock }}/{{ book.totalStock }}
              </n-tag>
            </n-space>
          </div>
        </n-space>
        
        <n-descriptions bordered :column="2">
          <n-descriptions-item label="ISBN">{{ book.isbn || '-' }}</n-descriptions-item>
          <n-descriptions-item label="分类">{{ book.categoryName || '-' }}</n-descriptions-item>
          <n-descriptions-item label="出版日期">{{ book.publishDate || '-' }}</n-descriptions-item>
          <n-descriptions-item label="借阅次数">{{ book.borrowCount || 0 }}</n-descriptions-item>
          <n-descriptions-item label="图书简介" :span="2">
            {{ book.description || '暂无简介' }}
          </n-descriptions-item>
        </n-descriptions>
        
        <n-space v-if="book.availableStock > 0">
          <n-button type="primary" size="large" @click="handleBorrow">
            <template #icon><BookmarkOutline /></template>
            立即借阅
          </n-button>
        </n-space>
      </n-space>
    </n-card>
    
    <n-spin v-else :show="loading" style="width: 100%; padding: 100px 0;">
      <n-empty description="加载中..." />
    </n-spin>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { bookApi } from '@/api/book'
import { borrowApi } from '@/api/borrow'
import { 
  NCard, NSpace, NAvatar, NTag, NDescriptions, NDescriptionsItem, 
  NButton, NSpin, NEmpty, useMessage 
} from 'naive-ui'
import { ArrowBackOutline, BookmarkOutline } from '@vicons/ionicons5'

const route = useRoute()
const router = useRouter()
const message = useMessage()

const loading = ref(false)
const book = ref(null)

const loadBook = async () => {
  loading.value = true
  try {
    const data = await bookApi.getBook(route.params.id)
    book.value = data
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleBorrow = async () => {
  try {
    await borrowApi.borrowBook(book.value.id)
    message.success('借阅成功')
    loadBook()
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => {
  loadBook()
})
</script>

<style scoped>
.book-detail {
  max-width: 900px;
}

h1 {
  margin: 0 0 16px 0;
  font-size: 28px;
}
</style>

